package cn.com.agameofthrones.AGoTLCGCards.Fragment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import cn.com.agameofthrones.AGoTLCGCards.Card;
import cn.com.agameofthrones.AGoTLCGCards.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SingleCardFragment extends Fragment {
	private String mCardID;
	private View mCardView;
	private Card mCard;
	boolean mViewImage=false; //by default, display text only.
	
//	public SingleCardFragment(String string) {
//		// TODO Auto-generated constructor stub
//		  mCardID=string;
//	}
	static SingleCardFragment newInstance(String id){
		SingleCardFragment f = new SingleCardFragment();

        // Supply card id input as an argument.
        Bundle args = new Bundle();
        args.putString("card_id", id);
        f.setArguments(args);

        return f;
	}
	@Override
	public View onCreateView( LayoutInflater inflater,  ViewGroup container,
	             Bundle savedInstanceState) {
		mCardID=getArguments().getString("card_id");
		mCard=new Card(mCardID, getActivity());
		mCardView=mCard.getView(mViewImage);
		
		String state = Environment.getExternalStorageState();
		//only to set click listener when we have a writable storage disk.
		if (Environment.MEDIA_MOUNTED.equals(state)) {//able to get a writable storage device. . 
			mCardView.setOnClickListener(new View.OnClickListener(){
				@Override
				public void onClick(View v) {
					//mViewImage=(mViewImage?false:true); //switch status
					if(!mViewImage){//current is text view , change to image view.
						if(mCard.isImageFileDownloaed()){//image file already there.
							mCard.switchViewType(mCardView,true);
							mViewImage=true;
						}else{// file not there, display dialog before download.
						DownloadImageAlertDialog dialog=DownloadImageAlertDialog.newInstance(
								R.string.downlad_image_alert_dialog_title);
						dialog.show(getFragmentManager(), "dialog");
						}
					}else{//from image to text view.
						mCard.switchViewType(mCardView,false);
						mViewImage=false;
					}
				}
			  }); 
		    } 		
		  return mCardView;
	  }
	
	@SuppressWarnings("unchecked")
	public void doDownloadAndSwitchView(){
		DownloadImageFileTask download_image_task=
				new DownloadImageFileTask(getActivity());
		HashMap<String,String> card_info=new HashMap<String,String>();
		card_info.put("set", mCard.getAttribute("sets_s"));
		card_info.put("id", mCard.getAttribute("cardID"));
		download_image_task.execute(card_info); //run the task in async mode.
		//mCard.switchViewType(mCardView, true);
	}
	//async task for image downloading
	class DownloadImageFileTask extends AsyncTask<Map<String,String>, Integer, Boolean> {
		int mLengthOfFile=0;// store length of the file.
		ProgressDialog mProgressDialog;
		HttpURLConnection mHCon; //we need this to gracefully disconnect http connection.
		
		
		public DownloadImageFileTask(Context context){
			 mProgressDialog = new ProgressDialog(context);
		}
		@Override
		protected void onPreExecute (){
			mProgressDialog.setMessage("Downloading image...");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.show();
		}
		@Override
		protected Boolean doInBackground(Map<String,String>... cards_info) {
	        try {
	           saveInternetFile(cards_info[0]);
	        } catch (Exception e) {
	        	//e.printStackTrace();
	        	publishProgress(100);//make progress dialog complete when download file failed
	        	return false;
	        }
	        return true;
		}
		
		private void saveInternetFile(Map<String,String> card_info) throws IOException {
			File storage_dir = Environment.getExternalStorageDirectory();
			String card_set=card_info.get("set");
			String card_id=card_info.get("id");
			try {
				String local_file_path=storage_dir+"/agotlcg/cards/"+card_set+"/"+card_id+".png";
				String remote_file_path="http://cards.gameharbor.com.cn/cards/"+
						card_set+"/"
						+card_id+".png";
				new File(local_file_path).getParentFile().mkdirs(); //create directory and file if necessary.
				BufferedOutputStream out = new BufferedOutputStream(
						new FileOutputStream(local_file_path),20*1024);
//				BufferedInputStream in = new BufferedInputStream(
//						connectNetwork(mRemoteFilePath),20*1024);
				InputStream in=connectNetwork(remote_file_path);
				byte buf[] = new byte[1024];
				int len;
				long total=0;
				while ((len = in.read(buf)) !=-1){
					total+=len;
					// publishing the progress....
	                publishProgress((int)(total*100/mLengthOfFile));
					out.write(buf, 0, len);
				}
				out.close();
				in.close();
				mHCon.disconnect();
			} catch (IOException e) {
				throw e;
			}
		}
		private InputStream connectNetwork(String card_image_url) throws IOException {
			InputStream ins = null;
			try {
				URL url = new URL(card_image_url);
				URLConnection connection = url.openConnection();
				mHCon = (HttpURLConnection) connection;
				
				int ResCode = mHCon.getResponseCode();
				//System.out.println("Responce Code is = " + ResCode);

				if (ResCode == HttpURLConnection.HTTP_OK) {
					mLengthOfFile=connection.getContentLength();
					InputStream url_ins = ((URLConnection) mHCon).getInputStream();
					ins=url_ins;
					//HCon.disconnect();
				} else {
					throw new IOException("network connection error.");
				}

			} catch (MalformedURLException e) {
				e.printStackTrace();//should not be here.
				//return null;
			} catch (IOException e) {
				throw e;
			}
			return ins;
		}
		
		@Override
		protected void onProgressUpdate (Integer... args){
			 mProgressDialog.setProgress(args[0]);
		}

		@Override
	    protected void onPostExecute(Boolean result) {
			if(result){//only swith view when download result is successful.
				mCard.switchViewType(mCardView,true);
			}else{
				//download failed.
				mViewImage=false;
			}
	        mProgressDialog.dismiss();        
	    }
	}

}
